package com.shop.operator.controller;

import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.shop.domain.Result;
import com.shop.model.ItemCat;
import com.shop.operator.service.impl.ItemCatServiceBean;
import com.shop.operator.service.impl.SpecificationServiceBean;

@Controller
@RequestMapping("/itemCat")
public class ItemCatAction {
	
	@Resource(name="itemCatServiceBean")
	ItemCatServiceBean itemCatServiceBean;
	
	@Resource(name="specificationSer")
	SpecificationServiceBean specificationService;
	
	@RequestMapping("/developForward")
	public String DevelopForward(){
		return "forward:/WEB-INF/operator/admin/item_cat.jsp";
	}
	
	
	/**
	 * 查找相同父Id的分类
	 * @param parentId 父id
	 * @return 返回查找的分类集合
	 */
	@RequestMapping("/findByParentId")
	@ResponseBody
	public List<ItemCat> findByParentId(long parentId){
		List<ItemCat> list = null;
//		request.setAttribute("level", level);
//		System.out.println(level);
		try {
			list = itemCatServiceBean.findByParentId(parentId);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		return list;
	}
	
	@RequestMapping("/createItemCat")
	@ResponseBody
	public Result createItemCat(@RequestBody ItemCat itemCat){
		try {
			itemCatServiceBean.add(itemCat);
			return new Result("添加成功:)");
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return new Result("添加失败:(");
		}
	}
	
	@RequestMapping("/deleteItemCat")
	@ResponseBody
	public Result deleteItemCat(@RequestBody List<Long> ids){
		try {
			for(long id:ids){
				if(!itemCatServiceBean.findByParentId(id).isEmpty()){
					return new Result("删除失败:( 不能删除存在下级的分类");
				};
			}
			itemCatServiceBean.delete(ids);
			return new Result("删除成功:)");
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return new Result("删除失败:(");
		}
		
	}
	@RequestMapping("/updateItemCat")
	@ResponseBody
	public Result updateItemCat(@RequestBody ItemCat itemCat){
		try {
			System.out.println(itemCat);
			itemCatServiceBean.update(itemCat);
			return new Result("更新成功:)");
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return new Result("更新失败:(");
		}
		
		
	}
	
	
	
	@RequestMapping("/findSpecList")
	@ResponseBody
	public List<Map> findSpecList(){
		return specificationService.findSpecList();
	}
}
